package com.hknc.btscale.utils;

import android.Manifest;
import android.app.Activity;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import pub.devrel.easypermissions.EasyPermissions;

public class DownloadUtils {
    public static void downloadFile(Activity activity, String dirName, String fileName, String urlStr, DownLoadListener listener) throws MalformedURLException {
        EasyPermissions.requestPermissions(activity, "", 1
                , new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS
                });

        createDir(dirName);

        URL url = new URL(urlStr);

        final long startTime = System.currentTimeMillis();
        Log.i("DOWNLOAD", "startTime=" + startTime);
        OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                e.printStackTrace();
//                activity.runOnUiThread(new Runnable() {
//                    public void run() {
//                        SingleToast.getInstance().toast(1, e.getMessage());
//                    }
//                });

                Log.e("DOWNLOAD", "download failed:" + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录

                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = createFile(dirName, fileName);
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中
                        listener.onDownloading(progress);

                    }
                    fos.flush();
                    // 下载完成
                    listener.onDownloadSuccess();

                    Log.i("DOWNLOAD", "download success totalTime=" + (System.currentTimeMillis() - startTime));
                } catch (Exception e) {
                    e.printStackTrace();
                    listener.onDownloadFailed();
                    Log.i("DOWNLOAD", "download failed");
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    /**
     * 在SD卡的指定目录上创建文件
     *
     * @param fileName
     */
    public static File createFile(String dirName, String fileName) {
        File file = new File(dirName, fileName);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static void createDir(String dirName) {
        //判断SD卡是否存在
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {

        }
        Log.d("TAG", "createDir: =============>" + dirName);
        File file = new File(dirName);
        if (!file.exists()) {
            file.mkdir();
        }
    }

    public interface DownLoadListener {
        void onDownloading(int progress);

        void onDownloadSuccess();

        void onDownloadFailed();
    }
}
